package com.zx.mes.upms.hyl.rest;

import com.zx.mes.hyl.common.msg.BaseResponse;
import com.zx.mes.hyl.common.msg.ObjectRestResponse;
import com.zx.mes.hyl.common.rest.BaseController;
import com.zx.mes.upms.hyl.biz.RoleBiz;
import com.zx.mes.upms.hyl.biz.UserBiz;
import com.zx.mes.upms.hyl.biz.UserRoleBiz;
import com.zx.mes.upms.hyl.entity.*;
import com.zx.mes.upms.hyl.pagemodel.Badge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 
 *
 * @author hyl
 * @email 632105841@qq.com
 * @date 2018-04-08 15:10:44
 */
@Controller
@RequestMapping("user")
public class UserController extends BaseController<UserBiz,User> {

    public static final String SPLIT_REGEX = ",";
    public static final String ANOTHER_STRING_SPANCE = "";

    @Autowired
    private UserRoleBiz userRoleBiz;

    @Autowired
    private RoleBiz roleBiz;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ObjectRestResponse<User> add(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return super.add(user);
    }

    @Override
    public ObjectRestResponse<User> update(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return super.update(user);
    }

    @GetMapping("/getRoleAll")
    @ResponseBody
    public ObjectRestResponse<Role> getRoleAll(){
        return new ObjectRestResponse<>().rel(true).data(roleBiz.selectListAll());
    }


    @GetMapping("/getRoleAndResourceByUserId")
    @ResponseBody
    public ObjectRestResponse<User> getRoleAndResourceByUserId(String id){
        return new ObjectRestResponse<>().rel(true).data(baseBiz.getRoleAndResourceByUserId(id));
    }

    @GetMapping("/getRoleByUserId")
    @ResponseBody
    public ObjectRestResponse<User> getRoleByUserId(String id){
        return new ObjectRestResponse<>().rel(true).data(baseBiz.getRoleByUserId(id));
    }

    @PostMapping("/insertUserAndRole")
    @ResponseBody
    public BaseResponse insertUserAndRole(String userId,String roleIds){
        if (userId !=null){
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRoleBiz.delete(userRole);

            if (roleIds !=null && !roleIds.equalsIgnoreCase(ANOTHER_STRING_SPANCE)){
                String[] roleId = roleIds.substring(0, roleIds.length() - 1).split(SPLIT_REGEX);
                for (String id:roleId){
                    userRole.setId(UUID.randomUUID().toString());
                    userRole.setRoleId(id);
                    userRoleBiz.insert(userRole);
                }
            }

        }
        return new BaseResponse(200,"插入成功!");
    }

    @GetMapping("/getUserAndRoleAndMenuByUserId")
    @ResponseBody
    public ObjectRestResponse<User> getUserAndRoleAndMenuByUserId(String id){
        return new ObjectRestResponse<>().rel(true).data(baseBiz.getUserAndRoleAndMenuByUserId(id));
    }

    @GetMapping("/getResourceByUserId")
    @ResponseBody
    public ObjectRestResponse<User> getResourceByUserId(String id, Authentication authentication){

        User user = new User();
        user.setResourceList(((User)authentication.getPrincipal()).getResourceList());

        return new ObjectRestResponse<>().rel(true).data(user);
    }

    @GetMapping("/getMenuByUserId")
    @ResponseBody
    public ObjectRestResponse<User> getMenuByUserId(String id){
        User user = baseBiz.getUserAndRoleAndMenuByUserId(id);
        List<Menu> list = new ArrayList<>(50);
        HashMap<String, Menu> map = new HashMap<>(50);
        if (user.getRoleList()!=null){
            for (int i=0;i<user.getRoleList().size();i++){
                list.addAll(user.getRoleList().get(i).getMenuList());
            }
            user.setMenuList(list);
        }
        //去重复值 (利用hashMap来去重)
        for (int j=0;j<user.getMenuList().size();j++){
            map.put(user.getMenuList().get(j).getId(), user.getMenuList().get(j));
        }

        List<Menu> menuList = new ArrayList<>(50);
        List<Menu> menuListParent = new ArrayList<>(50);
        List<Menu> menuListParentChildren = new ArrayList<>(50);
        Set<String> stringSet = map.keySet();
        for (String key:stringSet){
            menuList.add(map.get(key));
        }

        // 父子关系型展示
        for (int m=0;m<menuList.size();m++){
            if (menuList.get(m).getPid() == null || menuList.get(m).getPid().equalsIgnoreCase("")){
                menuListParent.add(menuList.get(m));
                menuListParentChildren.add(menuList.get(m));
            }
        }

        for (int n=0;n<menuListParent.size();n++){
            List<Menu> tempList = tempList=new ArrayList<>(10);
            for (int nn=0;nn<menuList.size();nn++){
                // menuList.get(nn).getPid().equalsIgnoreCase("") 防止pid是空字符串的情况
                if (menuList.get(nn).getPid() != null && !menuList.get(nn).getPid().equalsIgnoreCase("")) {
                    if (menuListParent.get(n).getId().equals(menuList.get(nn).getPid())) {
                        menuList.get(nn).setChildren(null);
                        tempList.add(menuList.get(nn));
                    }
                }
            }

            // 只要父菜单没有子菜单的都赋值为空
            if (tempList.size()==0){
                menuListParent.get(n).setChildren(null);
            }else{
                menuListParent.get(n).setChildren(tempList);
            }
        }


        user.setMenuList(menuListParent);
        return new ObjectRestResponse<>().rel(true).data(user);
    }

    private Badge setBadge(Menu menu){
        Badge badge = new Badge();
        if (menu.getText()==null || menu.getText().equals("")){
            badge.setText(menu.getText());
            badge.setVariant(menu.getVariant());
        }else {
            badge.setText(null);
            badge.setVariant(null);
        }
        return badge;
    }

    @Override
    public ObjectRestResponse<User> remove(@PathVariable String id) {
        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        // 清除中间表
        userRoleBiz.delete(userRole);
        // 再清除用户表中用户
        return super.remove(id);
    }
}